package com.aiex.framework.core.utils;

import com.aiex.framework.core.base.dto.BaseTreeDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class TreeUtils {

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public static <T extends BaseTreeDTO> List<T> toTree(List<T> list, Long parentId) {
        List<T> returnList = new ArrayList<>();
        for (T t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (Objects.equals(t.getParentId(), parentId)) {
                buildTree(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private static <T extends BaseTreeDTO> void buildTree(List<T> list, T t) {
        // 得到子节点列表
        List<T> childList = list.stream().filter(n -> Objects.equals(n.getParentId(), t.getId())).collect(Collectors.toList());
        t.setChildren(childList);
        for (T tChild : childList) {
            // 判断是否有子节点
            if (list.stream().anyMatch(n ->  Objects.equals(n.getParentId(), tChild.getId()))) {
                buildTree(list, tChild);
            }
        }
    }

}
